using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MallApi.Middlewares;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
{
  public void OnAuthorization(AuthorizationFilterContext context)
  {
    var userId = context.HttpContext.Items["UserId"];
    if (userId == null)
    {
      // 未经身份验证
      context.Result = new JsonResult(new { message = "未授权" })
      {
        StatusCode = StatusCodes.Status401Unauthorized
      };
    }
  }
}